package com.dataseek.iot.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dataseek.iot.device.entity.Profile;
import com.dataseek.iot.device.mapper.ProfileMapper;
import com.dataseek.iot.device.oss.FileUploadService;
import com.dataseek.iot.device.service.ProfileService;
import com.dataseek.iot.toolikit.common.service.IDServiceHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ProfileServiceImpl extends ServiceImpl<ProfileMapper, Profile> implements ProfileService {


    @Autowired
    private ProfileMapper profileMapper;

    @Autowired
    FileUploadService fileUploadService;

    @Autowired
    private IDServiceHelper idServiceHelper;


    @Override
    public Profile qryByUserId(String userId) {
        QueryWrapper<Profile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.getOne(queryWrapper);
    }

    @Override
    public Integer insertAction(Profile profile) {
        //先删除再插入
        QueryWrapper<Profile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", profile.getUserId());
        Profile tmpProfile = this.getOne(queryWrapper);
        if (tmpProfile != null) {
            profileMapper.delete(queryWrapper);
            fileUploadService.DeleteFile(tmpProfile.getImageUrl());
        }

        profile.setId(idServiceHelper.nextId());
        this.saveOrUpdate(profile);
        return 0;

    }
}
